<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>聊天</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <style>
        :root {
            --primary-color: #ffd700;
            --primary-light: #fff9e6;
            --text-color: #333;
            --border-color: #ffe066;
            --hover-color: #fff9e6;
            --message-sent: #ffd700;
            --message-received: #fff9e6;
            --shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
            --background-color: #fffdf6;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
        }

        body {
            background-color: var(--background-color);
            height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
        }

        .chat-container {
            width: 100%;
            max-width: 1200px;
            height: 80vh;
            background: white;
            border-radius: 16px;
            box-shadow: var(--shadow);
            display: flex;
            overflow: hidden;
        }

        .chat-list {
            width: 320px;
            border-right: 1px solid var(--border-color);
            display: flex;
            flex-direction: column;
            background: white;
        }

        .chat-list-header {
            padding: 20px;
            border-bottom: 1px solid var(--border-color);
            font-weight: bold;
            font-size: 18px;
            color: var(--text-color);
            background: var(--primary-light);
            position: sticky;
            top: 0;
            z-index: 1;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .chat-items {
            flex: 1;
            overflow-y: auto;
            padding: 10px 0;
        }

        .chat-item {
            padding: 12px 15px;
            display: flex;
            align-items: center;
            cursor: pointer;
            transition: all 0.3s ease;
            position: relative;
            border-bottom: 1px solid var(--border-color);
            gap: 12px;
            height: 68px;
        }

        .chat-item:hover {
            background: var(--hover-color);
        }

        .chat-item.active {
            background: var(--primary-light);
            border-right: 3px solid var(--primary-color);
        }

        .chat-avatar {
            width: 44px;
            height: 44px;
            border-radius: 50%;
            object-fit: cover;
            border: 2px solid var(--primary-color);
            flex-shrink: 0;
        }

        .chat-info {
            flex: 1;
            min-width: 0;
            display: flex;
            flex-direction: column;
            justify-content: center;
        }

        .chat-name {
            font-weight: 600;
            color: var(--text-color);
            font-size: 15px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .chat-content {
            flex: 1;
            display: flex;
            flex-direction: column;
            background: #fff;
        }

        .chat-header {
            padding: 15px 20px;
            border-bottom: 1px solid var(--border-color);
            background: var(--primary-light);
            display: flex;
            flex-direction: column;
            gap: 15px;
        }

        .chat-title {
            display: flex;
            align-items: center;
            gap: 5px;
            font-size: 18px;
            font-weight: 600;
            color: var(--text-color);
            padding: 0 10px;
            height: 44px;
        }

        .chat-title span {
            flex: 1;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            height: 44px;
            line-height: 44px;
            display: flex;
            align-items: center;
            margin-top: -2px;
        }

        .chat-title-avatar {
            width: 44px;
            height: 44px;
            border-radius: 50%;
            object-fit: cover;
            border: 2px solid var(--primary-color);
            flex-shrink: 0;
        }

        .product-info {
            display: flex;
            align-items: center;
            padding: 12px;
            background: white;
            border-radius: 12px;
            cursor: pointer;
            transition: all 0.3s ease;
            max-height: 100px;
            overflow: hidden;
            border: 1px solid var(--border-color);
        }

        .product-info:hover {
            background: #eee;
            transform: translateY(-1px);
        }

        .product-image {
            width: 80px;
            height: 80px;
            border-radius: 8px;
            object-fit: cover;
            margin-right: 12px;
            flex-shrink: 0;
            border: 1px solid var(--border-color);
            background-color: #f8f8f8;
        }

        .product-detail {
            flex: 1;
            min-width: 0;
            display: flex;
            flex-direction: column;
            justify-content: center;
            max-height: 80px;
            overflow: hidden;
        }

        .product-name {
            font-weight: 500;
            color: var(--text-color);
            margin-bottom: 8px;
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            line-height: 1.3;
            font-size: 14px;
            max-height: 36px;
        }

        .price-info {
            display: flex;
            align-items: baseline;
            gap: 8px;
        }

        .product-price {
            color: #ff4400;
            font-size: 16px;
            font-weight: bold;
        }

        .shipping-fee {
            color: #999;
            font-size: 12px;
        }

        .message-list {
            flex: 1;
            overflow-y: auto;
            padding: 20px;
            background: var(--background-color);
        }

        .message-bubble {
            margin-bottom: 20px;
            max-width: 70%;
            display: flex;
            align-items: flex-start;
            gap: 12px;
            position: relative;
            animation: fadeIn 0.3s ease;
        }

        .message-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            object-fit: cover;
            border: 2px solid var(--border-color);
            flex-shrink: 0;
        }

        .message-sent {
            flex-direction: row-reverse;
            margin-left: auto;
        }

        .message-received {
            flex-direction: row;
            margin-right: auto;
        }

        .message-content-wrapper {
            display: flex;
            flex-direction: column;
            max-width: calc(100% - 52px);
            margin-top: 0;
        }

        .message-content {
            padding: 12px 16px;
            border-radius: 16px;
            position: relative;
            word-break: break-word;
            line-height: 1.4;
            font-size: 14px;
            margin-bottom: 4px;
        }

        .message-sent .message-content {
            background: var(--message-sent);
            border-bottom-right-radius: 4px;
            color: #000;
        }

        .message-received .message-content {
            background: var(--message-received);
            border-bottom-left-radius: 4px;
            color: #000;
        }

        .message-time {
            font-size: 12px;
            color: #999;
            margin-top: 2px;
            align-self: flex-end;
        }

        .message-status {
            font-size: 12px;
            color: #666;
            margin-top: 2px;
            text-align: right;
        }

        .message-input {
            padding: 20px;
            background: var(--primary-light);
            border-top: 1px solid var(--border-color);
        }

        .input-box {
            display: flex;
            gap: 12px;
            align-items: flex-end;
        }

        textarea {
            flex: 1;
            padding: 12px 16px;
            border: 1px solid var(--border-color);
            border-radius: 12px;
            resize: none;
            height: 80px;
            font-size: 14px;
            line-height: 1.4;
            transition: all 0.3s ease;
        }

        textarea:focus {
            outline: none;
            border-color: var(--primary-color);
            box-shadow: 0 0 0 2px var(--primary-light);
        }

        .send-btn {
            padding: 12px 24px;
            background: var(--primary-color);
            color: #000;
            border: none;
            border-radius: 12px;
            cursor: pointer;
            font-weight: 600;
            font-size: 14px;
            height: 45px;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .send-btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 2px 8px rgba(255, 215, 0, 0.4);
        }

        .send-btn i {
            font-size: 16px;
        }

        .unread-count {
            background: #ff4400;
            color: white;
            min-width: 20px;
            height: 20px;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            font-weight: bold;
            position: absolute;
            right: 15px;
            top: 15px;
            padding: 0 6px;
        }

        .no-chat {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100%;
            color: #999;
            gap: 15px;
            padding: 20px;
            text-align: center;
        }

        .no-chat i {
            font-size: 48px;
            color: var(--primary-color);
        }

        /* 滚动条美化 */
        ::-webkit-scrollbar {
            width: 6px;
        }

        ::-webkit-scrollbar-track {
            background: #f1f1f1;
        }

        ::-webkit-scrollbar-thumb {
            background: #ccc;
            border-radius: 3px;
        }

        ::-webkit-scrollbar-thumb:hover {
            background: #999;
        }

        /* 适配移动端 */
        @media (max-width: 768px) {
            .chat-container {
                height: 100vh;
                border-radius: 0;
            }

            .chat-list {
                width: 280px;
            }

            body {
                padding: 0;
            }
        }

        .chat-product-image {
            width: 44px;
            height: 44px;
            border-radius: 6px;
            object-fit: cover;
            flex-shrink: 0;
            border: 1px solid var(--border-color);
            background-color: #f8f8f8;
            margin-left: auto;
        }

        .back-button {
            padding: 8px 16px;
            background: var(--primary-color);
            color: #000;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-weight: 600;
            font-size: 14px;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .back-button:hover {
            transform: translateY(-1px);
            box-shadow: 0 2px 8px rgba(255, 215, 0, 0.4);
        }

        .system-notification {
            display: flex;
            justify-content: center;
            margin: 10px 0;
            background: none !important;
            box-shadow: none !important;
        }

        .notification-content {
            background: rgba(255, 215, 0, 0.1);
            border: 1px solid var(--primary-color);
            border-radius: 8px;
            padding: 10px 15px;
            text-align: center;
            max-width: 80%;
        }

        .notification-content img {
            border-radius: 8px;
            margin-bottom: 8px;
            cursor: pointer;
            transition: transform 0.3s ease;
        }

        .notification-content img:hover {
            transform: scale(1.02);
        }

        .notification-content a {
            text-decoration: none;
            color: inherit;
        }

        .system-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: var(--primary-color);
            display: flex;
            align-items: center;
            justify-content: center;
            flex-shrink: 0;
        }

        .system-avatar i {
            font-size: 20px;
            color: #fff;
        }

        .system-message {
            background: var(--message-received);
            border: 1px solid var(--border-color);
            padding: 12px 16px;
            border-radius: 16px;
            border-bottom-left-radius: 4px;
            max-width: 100%;
        }

        .system-message img {
            border-radius: 8px;
            margin: -12px -16px 8px -16px;
            width: calc(100% + 32px);
            max-width: none;
            height: 150px;
            object-fit: cover;
        }

        .system-message a {
            text-decoration: none;
            color: inherit;
            display: block;
        }

        .system-message a:hover img {
            opacity: 0.9;
        }

        .message-received .system-message {
            margin-left: 12px;
        }

        .message-sent {
            flex-direction: row-reverse;
            margin-left: auto;
        }

        .message-received {
            flex-direction: row;
            margin-right: auto;
        }

        .message-sent .message-content {
            background: var(--message-sent);
            border-bottom-right-radius: 4px;
            margin-right: 12px;
        }

        .message-received .message-content {
            background: var(--message-received);
            border-bottom-left-radius: 4px;
            margin-left: 12px;
        }

        .message-content-wrapper {
            max-width: calc(100% - 60px);
        }

        .message-bubble {
            display: flex;
            align-items: flex-start;
            margin-bottom: 20px;
            max-width: 70%;
        }
    </style>
</head>
<body>
    <div class="chat-container">
        <div class="chat-list">
            <div class="chat-list-header">
                <i class="fas fa-comments"></i> 聊天列表
                <button class="back-button" onclick="goBack()">
                    <i class="fas fa-arrow-left"></i>
                    返回
                </button>
            </div>
            <div class="chat-items" id="chatList">
                <!-- 聊天列表将通过JavaScript动态加载 -->
            </div>
        </div>
        <div class="chat-content">
            <div class="chat-header">
                <div class="chat-title">
                    <i class="fas fa-user"></i>
                    <span id="chatUserName">与 xxx 的对话</span>
                </div>
                <div class="product-info" id="productInfo" style="display: none;" onclick="goToProduct()">
                    <img class="product-image" src="" alt="商品图片">
                    <div class="product-detail">
                        <div class="product-name"></div>
                        <div class="price-info">
                            <div class="product-price">¥<span class="price-value"></span></div>
                            <div class="shipping-fee">含运费¥<span class="shipping-value">0.00</span></div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="message-list" id="messageList">
                <!-- 消息列表将通过JavaScript动态加载 -->
            </div>
            <div class="message-input">
                <div class="input-box">
                    <textarea id="messageInput" placeholder="输入消息...按Enter发送，Shift+Enter换行"></textarea>
                    <button class="send-btn" onclick="sendMessage()">
                        <i class="fas fa-paper-plane"></i>
                        发送
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script>
        let ws;
        let currentReceiverId;
        let currentProductId = null;  // 添加全局变量存储当前商品ID
        let currentReceiverAvatar = '';  // 添加全局变量存储当前聊天对象的头像
        let currentReceiverName = '';    // 添加全局变量存储当前聊天对象的昵称

        function connectWebSocket() {
            $.ajax({
                url: '/user/get-user',
                type: 'GET',
                success: function(response) {
                    if (response.state === 1) {
                        window.currentUserId = response.data.id;  // 保存当前用户ID
                        window.currentUserAvatar = response.data.avatar;  // 保存当前用户头像
                        window.currentUserNickname = response.data.nickname;  // 保存当前用户昵称
                        
                        // 建立WebSocket连接
                        ws = new WebSocket('ws://localhost:9000/chat');
                        
                        ws.onopen = function() {
                            console.log('WebSocket连接已建立');
                            
                            // 先加载聊天列表
                            loadChatList();
                            
                            // 然后检查URL参数
                            const urlParams = new URLSearchParams(window.location.search);
                            const sellerId = urlParams.get('sellerId');
                            const urlProductId = urlParams.get('productId');
                            
                            // 如果有sellerId参数，需要等待聊天列表加载完成后再加载消息
                            if (sellerId) {
                                // 使用setTimeout确保聊天列表已
                                setTimeout(() => {
                                    const chatItem = $(`.chat-item[onclick*="loadMessages(${sellerId},"]`);
                                    if (chatItem.length > 0) {
                                        // 触发点击事件，这样会自动调用loadMessages并传递正确的用户信息
                                        chatItem.click();
                                    } else {
                                        // 如果在聊天列表中找不到，可能是新对话，需要额外加载卖家信息
                                        $.ajax({
                                            url: `/user/get-user-info/${sellerId}`,
                                            type: 'GET',
                                            success: function(response) {
                                                if (response.state === 1) {
                                                    const user = response.data;
                                                    loadMessages(parseInt(sellerId), urlProductId, user.nickname, user.avatar);
                                                }
                                            }
                                        });
                                    }
                                }, 100);
                            }
                        };
                        
                        ws.onmessage = function(event) {
                            console.log('Received message:', event.data);
                            const message = JSON.parse(event.data);
                            console.log("笑傲",message);
                            
                            if (message.senderId === currentReceiverId) {
                                appendMessage({
                                    ...message,
                                    senderAvatar: message.senderAvatar,  // 直接使用senderAvatar字段
                                    senderName: message.senderName       // 直接使用senderName字段
                                }, false);
                                
                                // 发送已读回执
                                $.ajax({
                                    url: `/chat/read/${message.senderId}`,
                                    type: 'POST',
                                    success: function() {
                                        // 通知发送者消息已读
                                        ws.send(JSON.stringify({
                                            type: 'read_receipt',
                                            receiverId: message.senderId,
                                            messageId: message.id
                                        }));
                                    }
                                });
                            } else if (message.type === 'read_receipt') {
                                // 更新消息状态为已读
                                updateMessageStatus();
                            }
                            
                            loadChatList();
                        };
                        
                        ws.onclose = function() {
                            console.log('WebSocket连接已关闭');
                            setTimeout(connectWebSocket, 1000);
                        };
                    } else {
                        location.href = 'login.html';
                    }
                }
            });
        }

        function loadChatList() {
            $.ajax({
                url: '/chat/list',
                type: 'GET',
                success: function(response) {
                    if (response.state === 1) {
                        renderChatList(response.data);
                    }
                }
            });
        }

        function loadMessages(receiverId, urlProductId, userName = '', userAvatar = '') {
            if (!receiverId) return;
            
            currentReceiverId = receiverId;
            currentReceiverAvatar = userAvatar;
            currentReceiverName = userName;
            $('#messageList').empty();

            // 如果是系统通知消息（ID为7），特殊处理
            if (receiverId === 7) {
                $('#chatUserName').html(`
                    <div style="display: flex; align-items: center; gap: 12px;">
                        <i class="fas fa-bell" style="font-size: 24px; color: var(--primary-color);"></i>
                        <span>系统通知</span>
                    </div>
                `);
                // 隐藏商品信息和输入框
                $('#productInfo').hide();
                $('.message-input').hide();
            } else {
                // 普通用户消息
                $('#chatUserName').html(`
                    <div style="display: flex; align-items: center; gap: 12px;">
                        <img src="${userAvatar}" alt="${userName}" class="chat-title-avatar" onclick="goToUserHome(${receiverId})" style="cursor: pointer;">
                        <span>${userName}</span>
                    </div>
                `);
                // 显示输入框和商品信息
                $('.message-input').show();
                if (urlProductId) {
                    loadProductInfo(urlProductId);
                } else {
                    $('#productInfo').hide();
                }
            }

            // 发送已读请求
            $.ajax({
                url: `/chat/read/${receiverId}`,
                type: 'POST',
                success: function() {
                    loadChatList();
                }
            });

            // 加载消息记录
            $.ajax({
                url: `/chat/messages/${receiverId}`,
                type: 'GET',
                success: function(response) {
                    if (response.state === 1) {
                        const messages = response.data;
                        if (receiverId !== 7 && !urlProductId && messages && messages.length > 0) {
                            const latestMessage = messages[messages.length - 1];
                            if (latestMessage.productId) {
                                loadProductInfo(latestMessage.productId);
                            }
                        }
                        renderMessages(messages);
                        $('.chat-item').removeClass('active');
                        $(`.chat-item[onclick*="loadMessages(${receiverId})"]`).addClass('active');
                        scrollToBottom();
                    }
                }
            });
        }

        function sendMessage() {
            const content = $('#messageInput').val().trim();
            if (!content) {
                alert('请输入消息内容');
                return;
            }

            // 不允许向系统通知发送消息
            if (currentReceiverId === 7) {
                alert('无法向系统发送消息');
                return;
            }

            const message = {
                receiverId: currentReceiverId,
                content: content,
                productId: currentProductId
            };

            if (ws && ws.readyState === WebSocket.OPEN) {
                ws.send(JSON.stringify(message));
                $('#messageInput').val('');
                appendMessage({
                    content: content,
                    createTime: new Date(),
                    senderId: window.currentUserId,
                    status: 0
                }, true);
            } else {
                alert('WebSocket连接已断开，请刷新页面重试');
            }
        }

        function appendMessage(message, isCurrentUser) {
            const messageList = $('.message-list');
            let messageHtml = '';
            
            // 系统通知消息特殊处理（senderId = 7）
            if (message.senderId === 7) {
                messageHtml = `
                    <div class="message-bubble message-received">
                        <div class="system-avatar">
                            <i class="fas fa-bell"></i>
                        </div>
                        <div class="message-content system-message">
                            ${message.content}
                        </div>
                    </div>
                `;
            } else {
                // 普通用户消息
                const messageContent = message.contentType === 'HTML' ? 
                    message.content : 
                    $('<div>').text(message.content).html();
                    
                messageHtml = `
                    <div class="message-bubble ${isCurrentUser ? 'message-sent' : 'message-received'}">
                        <img src="${isCurrentUser ? window.currentUserAvatar : currentReceiverAvatar}" 
                             class="message-avatar" 
                             alt="${isCurrentUser ? window.currentUserNickname : currentReceiverName}">
                        <div class="message-content-wrapper">
                            <div class="message-content">
                                ${messageContent}
                            </div>
                            <div style="display: flex; justify-content: ${isCurrentUser ? 'flex-end' : 'flex-start'}; gap: 8px; align-items: center;">
                                <div class="message-time">${formatTime(message.createTime)}</div>
                                ${isCurrentUser && message.status === 1 ? '<div class="message-status">已读</div>' : ''}
                            </div>
                        </div>
                    </div>
                `;
            }
            
            messageList.append(messageHtml);
            messageList.scrollTop(messageList[0].scrollHeight);
        }

        function scrollToBottom() {
            const messageList = document.getElementById('messageList');
            messageList.scrollTop = messageList.scrollHeight;
        }

        function renderChatList(chatList) {
            if (!chatList || chatList.length === 0) {
                $('#chatList').html('<div class="no-chat">暂无聊天记录</div>');
                return;
            }

            // 获取URL中的商品ID和卖家ID
            const urlParams = new URLSearchParams(window.location.search);
            const urlProductId = urlParams.get('productId');
            const urlSellerId = urlParams.get('sellerId');

            // 确保系统通知始终在第一位
            const systemNotification = chatList.find(chat => chat.userId === 7);
            const otherChats = chatList.filter(chat => chat.userId !== 7);
            const sortedChatList = systemNotification ? [systemNotification, ...otherChats] : otherChats;

            const listHtml = sortedChatList.map(chat => {
                // 如果是系统通知
                if (chat.userId === 7) {
                    return `
                        <div class="chat-item ${chat.userId === currentReceiverId ? 'active' : ''}" 
                             onclick="loadMessages(${chat.userId}, null, '系统通知', null)">
                            <i class="fas fa-bell" style="font-size: 24px; color: var(--primary-color); width: 44px; height: 44px; display: flex; align-items: center; justify-content: center;"></i>
                            <div class="chat-info">
                                <div class="chat-name">系统通知</div>
                            </div>
                            ${chat.unreadCount > 0 ? `<span class="unread-count">${chat.unreadCount}</span>` : ''}
                        </div>
                    `;
                }

                // 如果是当前聊天的卖家且有URL商品ID，使用URL中的商品信息
                if (urlProductId && chat.userId === parseInt(urlSellerId)) {
                    $.ajax({
                        url: `/product/detail?id=${urlProductId}`,
                        type: 'GET',
                        async: false,
                        success: function(response) {
                            if (response.state === 1) {
                                const product = response.data[0];
                                chat.productImage = JSON.parse(product.images)[0];
                                chat.productName = product.name;
                                chat.productPrice = product.price;
                                chat.productId = parseInt(urlProductId);
                            }
                        }
                    });
                }

                return `
                    <div class="chat-item ${chat.userId === currentReceiverId ? 'active' : ''}" 
                         onclick="loadMessages(${chat.userId}, ${chat.userId === parseInt(urlSellerId) ? urlProductId : null}, '${chat.userName}', '${chat.userAvatar}')">
                        <img src="${chat.userAvatar}" class="chat-avatar" alt="用户头像">
                        <div class="chat-info">
                            <div class="chat-name">${chat.userName}</div>
                        </div>
                        ${chat.productImage ? `
                            <img src="${chat.productImage}" 
                                 class="chat-product-image" 
                                 alt="商品图片"
                                 title="￥${chat.productPrice} - ${chat.productName}"
                            >
                        ` : ''}
                        ${chat.unreadCount > 0 ? `<span class="unread-count">${chat.unreadCount}</span>` : ''}
                    </div>
                `;
            }).join('');
            
            $('#chatList').html(listHtml);
        }

        function renderMessages(messages) {
            const messageList = $('#messageList');
            messages.forEach(message => {
                appendMessage(message, message.senderId === getUserId());
            });
            scrollToBottom();
        }

        // 获取当前用户ID的函数
        function getUserId() {
            // 这里需要从后端获取或从session中获
            return window.currentUserId;
        }

        // 修改时间格式化函数，���显示时间
        function formatTime(time) {
            if (!time) return '';
            const date = new Date(time);
            return date.toLocaleTimeString('zh-CN', {
                hour: '2-digit',
                minute: '2-digit'
            });
        }

        // 添加回车发送功能
        $('#messageInput').on('keypress', function(e) {
            if (e.which === 13 && !e.shiftKey) {  // Enter键发送，Shift+Enter换行
                e.preventDefault();
                sendMessage();
            }
        });

        // 页面加载时连接WebSocket
        $(document).ready(function() {
            // 先连接WebSocket
            connectWebSocket();
        });

        // 添加商品跳转函数
        function goToProduct() {
            if (currentProductId) {
                window.open(`product-detail.html?id=${currentProductId}`, '_blank');
            }
        }

        // 添加消息状态更新函数
        function updateMessageStatus() {
            $('.message-sent').each(function() {
                if (!$(this).find('.message-status').length) {
                    $(this).append('<div class="message-status">已读</div>');
                }
            });
        }

        // 添加返回函数
        function goBack() {
            // 如果是从商品详情页来的，返回上一页
            if (document.referrer.includes('product-detail.html')) {
                window.history.back();
            } else {
                // 否则返回首页
                window.location.href = 'home.html';
            }
        }

        // 添加跳转到用户主页的函数
        function goToUserHome(userId) {
            if (userId) {
                window.open(`user-profile.html?id=${userId}`, '_blank');
            }
        }

        // 添加加载商品信息的辅助函数
        function loadProductInfo(productId) {
            $.ajax({
                url: `/product/detail?id=${productId}`,
                type: 'GET',
                success: function(response) {
                    if (response.state === 1) {
                        const product = response.data[0];
                        currentProductId = parseInt(productId);
                        $('#productInfo').show();
                        $('#productInfo .product-image').attr('src', JSON.parse(product.images)[0]);
                        $('#productInfo .product-name').text(product.name);
                        $('.price-value').text(product.price);
                        $('.shipping-value').text('0.00');
                    }
                }
            });
        }
    </script>
</body>
</html> 